// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: adapter implementation

#include "baidu_ca_adapter.h"
#include "baidu_ca_memory_adapter.h"
#include "baidu_ca_network_adapter.h"
#include "timer.h"
#include "rtos.h"

static mbed::Timer s_timer;
static volatile bool s_isInitialized = false;
static volatile bool s_isTimerStarted = false;

static bca_u32_t bca_timestamp() {
    if (!s_isTimerStarted) {
        s_timer.start();
        s_isTimerStarted = true;
    }

    return s_timer.read_ms();
}

using rtos::Thread;

void bca_sleep(bca_u32_t ms) {
	Thread::wait(ms);
}

static void bca_debug(bca_context ctx,
                      bca_u32_t level,
                      const char* file,
                      bca_u32_t line,
                      const char* msg) {
    if (file) {
        fprintf(reinterpret_cast<FILE*>(ctx), "[%d] %s(%4d): %s", level, file, line, msg);
    } else {
        fprintf(reinterpret_cast<FILE*>(ctx), "[%d] %s", level, msg);
    }
}

int baidu_ca_is_initialized() {
    return s_isInitialized;
}

void baidu_ca_initialize() {
    if (s_isInitialized) {
        return ;
    }

    s_isInitialized = true;
    baidu_ca_memory_init(NULL,
            bca_memory_alloc,
            bca_memory_realloc,
            bca_memory_free);
    baidu_ca_timestamp_init(bca_timestamp);
    baidu_ca_debug_init(stdout, bca_debug);
    baidu_ca_transport_init(
            bca_soc_create,
            bca_soc_connect,
            bca_soc_send,
            bca_soc_recv,
            NULL,
            bca_soc_close,
            bca_soc_destroy);
#if 0
    baidu_ca_mutex_init(my_mutex_create,
                        my_mutex_lock,
                        my_mutex_unlock,
                        my_mutex_destroy);
#endif
}

